import { defineStore } from "pinia";
import { ref } from "vue";
import config from "@/config/config.json";
import { getToken } from "@/utils/auth";
import Toast from "@vant/weapp/dist/toast/toast";

export const useDetailSessionStore = defineStore("detailSession-store", () => {
  const chatText = ref("");
  function Uint8ArrayToString(fileData) {
    let uint8Array = new Uint8Array(fileData);
    let text = "";
    for (let i = 0; i < uint8Array.length; i++) {
      text += String.fromCharCode(uint8Array[i]);
    }
    return text;
  }

  function sendAiCreate(data) {
    Toast.loading("生成中");
    const request = uni.request({
      url: `${config.siteDomain}${
        import.meta.env.VITE_GLOB_API_URL
      }/chat_message/sendAiCreate`,
      method: "POST",
      responseType: "arraybuffer",
      enableChunked: true, // 是否是流式传输
      header: {
        "content-type": "application/json",
        satoken: getToken(),
      },
      data,
      success(res) {},
      fail(err) {},
    });
    request.onChunkReceived((res) => {
      Toast.clear();
      let text = Uint8ArrayToString(res.data);
      text = decodeURIComponent(escape(text));

      let lastText = text.split("\n");

      chatText.value = JSON.parse(lastText[lastText.length - 1]).text;
    });
  }

  return {
    chatText,
    sendAiCreate,
  };
});
